package com.jilian.mydemo.modul.exam.ui;

import android.annotation.SuppressLint;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.BaseEventMsg;
import com.jilian.mydemo.common.dto.CollectRefreshDto;
import com.jilian.mydemo.common.dto.VideoArticlesDto;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.event.RxBus;
import com.jilian.mydemo.modul.user.viewmodel.UserViewModel;
import com.jilian.mydemo.utils.BtiMapUtils;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.WxShareUtils;

import java.util.List;

import cn.jzvd.JzvdStd;

/**
 * 文章详情
 */
public class ArticleCetailsActivity extends BaseActivity {
    private String id;
    //private ImageView ivHead;
    private UserViewModel userViewModel;
    //收藏图标
    private ImageView imageView;
    private WebView webview;
    private JzvdStd ivVideo;




//    @Override
//    protected void onResume() {        super.onResume();        //home back
//        JzvdStd.goOnPlayOnResume();
//    }    @Override
    protected void onPause() {        super.onPause();   //     Jzvd.clearSavedProgress(this, null);
        //home back
        JzvdStd.goOnPlayOnPause();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }
    @Override
    protected void createViewModel() {
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_articlecetails;
    }

    @Override
    public void initView() {
        webview = (WebView) findViewById(R.id.webview);
        imageView = (ImageView) findViewById(R.id.iv_right_two);
        setrightImageOne(R.drawable.image_share, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                share();
            }
        });
        setrightImageTwo(R.drawable.image_collection, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //收藏
                collect();
            }
        });
       // ivHead = (ImageView) findViewById(R.id.iv_head);
        ivVideo = (JzvdStd) findViewById(R.id.iv_video);

    }
    /**
     * 加载html标签
     *
     * @param bodyHTML
     * @return
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto!important;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
    private void share() {
        showDialog();
    }

    /**
     * 购买。添加购物车对话框
     */
    private void showDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_share)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        TextView tvCancel = (TextView) holder.getView((R.id.tv_cancel));
                        LinearLayout llOne = (LinearLayout) holder.getView(R.id.ll_one);
                        LinearLayout llTwo = (LinearLayout) holder.getView(R.id.ll_two);

                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });

                        //微信
                        llOne.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                shareTextWXSceneSession();
                            }
                        });
                        //微信朋友圈
                        llTwo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                shareTextWXSceneTimeline();
                            }
                        });


                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }



    private void shareTextWXSceneSession() {
        WxShareUtils.shareTextWXSceneSession("微信分享SDK测试");

    }
    private void shareTextWXSceneTimeline() {
        WxShareUtils.shareTextWXSceneTimeline("微信分享SDK测试");

    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }


    private int isCollect;

    private void collect() {
        showLoadingDialog();
        userViewModel.addCollect(Long.parseLong(id), isCollect);
        userViewModel.getCollectliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto dto) {
                hideLoadingDialog();
                if (dto.isSuccess()) {
                    getDetail();
                    //通知刷新UI
                    if ("1".equals(getIntent().getStringExtra("param"))) {
                        CollectRefreshDto refreshDto = new CollectRefreshDto();
                        refreshDto.setCode(100);
                        BaseEventMsg msg = new BaseEventMsg();
                        msg.setCollectRefreshDto(refreshDto);
                        RxBus.getInstance().post(msg);
                    }

                    if (isCollect == 1) {
                        ToastUitl.showImageToastSuccess("收藏成功");
                        imageView.setImageResource(R.drawable.image_collect_select);
                    } else {
                        ToastUitl.showImageToastSuccess("取消收藏成功");
                        imageView.setImageResource(R.drawable.image_collection);
                    }

                } else {
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }

    @Override
    public void initData() {
        id =  getIntent().getStringExtra("id");
        setNormalTitle(getIntent().getStringExtra("title"), v -> finish());
        showLoadingDialog();
        getDetail();


    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            getLoadingDialog().dismiss();
            if (msg.what == 1000) {
                VideoArticlesDto dto = (VideoArticlesDto) msg.obj;
                ivVideo.setUp(dto.getPath(), "",JzvdStd.SCREEN_WINDOW_NORMAL);
                ivVideo.thumbImageView.setImageBitmap(dto.getBitmap());
                JzvdStd.setJzUserAction(null);
                ivVideo.setVisibility(View.VISIBLE);
                hideLoadingDialog();

            }
        }
    };



    /**
     * 获取详情接口
     */
    private void getDetail() {

        userViewModel.queryAppArticleDetail(id);
        userViewModel.getArticlesDetailliveData().observe(this, new Observer<BaseDto<VideoArticlesDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<VideoArticlesDto> videoArticlesDtoBaseDto) {
                hideLoadingDialog();
                if (videoArticlesDtoBaseDto.isSuccess() && videoArticlesDtoBaseDto.getData() != null) {
                    //content是后台返回的h5标签
                    webview.loadDataWithBaseURL(null,
                            getHtmlData(videoArticlesDtoBaseDto.getData().getContent()), "text/html", "utf-8", null);
//                    //图片
//                    if(videoArticlesDtoBaseDto.getData().getType()==1){
//                        hideLoadingDialog();
//                        Glide
//                                .with(ArticleCetailsActivity.this)
//                                .load(videoArticlesDtoBaseDto.getData().getPath())
//                                .into(ivHead);
//                        ivHead.setVisibility(View.VISIBLE);
//                        ivVideo.setVisibility(View.GONE);
//                    }
                    //视频
                    if(videoArticlesDtoBaseDto.getData().getType()==2){
                        showLoadingDialog();
                        ivVideo.setVisibility(View.INVISIBLE);
                        //开启子线程
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                //对视频封面处理 耗时操作

                                        //处理视频封面
                                videoArticlesDtoBaseDto.getData().setBitmap(BtiMapUtils.getNetVideoBitmap(videoArticlesDtoBaseDto.getData().getPath()));
                                Message msg = Message.obtain();
                                msg.what = 1000;
                                msg.obj = videoArticlesDtoBaseDto.getData();
                                handler.sendMessage(msg);
                            }
                        }.start();
                    }

                    //是否收藏
                    if (videoArticlesDtoBaseDto.getData().getIsCollect() == 1) {
                        imageView.setImageResource(R.drawable.image_collect_select);
                        isCollect = 0;

                    } else {
                        imageView.setImageResource(R.drawable.image_collection);
                        isCollect = 1;

                    }
                } else {
                    ToastUitl.showImageToastTips(videoArticlesDtoBaseDto.getMsg());
                }

            }
        });
    }


    @Override
    public void initListener() {

    }
}
